package com.itheima.reggie.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    // 权限校验拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.取出请求头
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) { // 为空或为空串
            // 拦截并返回错误
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = JSON.toJSONString(resultInfo); // 阿里巴巴提供json转换工具
            response.getWriter().write(json);
            return false;
        }
        // 处理Bearer
        token = token.replace("Bearer ", "");

        // 2.jwt解析token
        Map calims = JwtUtil.parseToken(token);
        if (calims == null) { // 为空
            // 拦截并返回错误
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = JSON.toJSONString(resultInfo); // 阿里巴巴提供json转换工具
            response.getWriter().write(json);
            return false;
        }
        // 3.取出手机号查询redis
        String phone = (String) calims.get("phone");
        User user = (com.itheima.reggie.domain.User) redisTemplate.opsForValue().get("phone:" + phone);

        // 4.判断是否有值
        if (user==null) {
            // 拦截并返回错误
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = JSON.toJSONString(resultInfo); // 阿里巴巴提供json转换工具
            response.getWriter().write(json);
            return false;
        }

        // 5.授权成功，放行
        // 5-1 redis 续期
        redisTemplate.opsForValue().set("phone:" + phone, user, Duration.ofDays(1));
        // 5-2存入线程内
        UserHolder.set(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}